﻿using UnityEngine;
using System.Collections;
using System.IO;


public class PhotoOperation
{

		public delegate void OnLoadSuccess( Texture2D tex );
		public delegate void OnLoadFailed( string err );

		public static void FileLoad(string path,OnLoadSuccess suc,OnLoadFailed err)
		{
				try
				{
						Texture2D texture = new Texture2D(2,2);

						texture.LoadImage(ReadPNG(path));

						suc(texture);
				}

				catch( DirectoryNotFoundException e ) {
                        err(e.Message);
				}
        catch (EndOfStreamException e)
        {
            err(e.Message);
        }
        catch (FileLoadException e)
        {
            err(e.Message);
        }
        catch (FileNotFoundException e)
        {
            err(e.Message);
        }
        catch (PathTooLongException e)
        {
            err(e.Message);
        }
        catch (IOException e)
        {
            err(e.Message);
        }
    }


		public static byte[] ReadPNG(string path)
		{
				FileStream fileStream = new FileStream(path, FileMode.Open, System.IO.FileAccess.Read);

				fileStream.Seek(0, SeekOrigin.Begin);

				byte[] binary = new byte[fileStream.Length]; //创建文件长度的buffer

				fileStream.Read(binary, 0, (int)fileStream.Length);

				fileStream.Close();

				fileStream.Dispose();

				fileStream = null;

				return binary;
		}


    public static byte[] ReadToBinary(string path)
    {
        FileStream fileStream = new FileStream(path, FileMode.Open, System.IO.FileAccess.Read);

        fileStream.Seek(0, SeekOrigin.Begin);

        byte[] binary = new byte[fileStream.Length]; //创建文件长度的buffer

        fileStream.Read(binary, 0, (int)fileStream.Length);

        fileStream.Close();

        fileStream.Dispose();

        fileStream = null;

        return binary;
    }


	// 从摄像机截图返回texture
	public static Texture2D CameraCaputre(Camera cam, UnityEngine.Rect rect = default(Rect))
	{
		if (rect == default(Rect))
			rect = new Rect ( 0,0,Screen.width, Screen.height );

		RenderTexture rt = new RenderTexture ((int)rect.width, (int)rect.height, 0);

		cam.targetTexture = rt;
		cam.Render ();

		RenderTexture.active = rt;

		Texture2D t2d = new Texture2D( Screen.width, Screen.height, TextureFormat.RGB24, false);
		t2d.ReadPixels ( new Rect(0,0,Screen.width, Screen.height), 0,0 );
		t2d.Apply ();

		cam.targetTexture = null;
		RenderTexture.active = null;

		return t2d;

	}


}

